<template>
  <div class="graph-analyze">
    <div
      v-if="knowledgeTree"
      ref="knowledgeDrawer"
      class="knowledge-drawer"
      :style="{
        transform: open ? 'translate(0vw,-50%)' : 'translate(-18vw,-50%)',
        transition: 'all 0.3s ease',
        boxShadow: open ? '' : '0 0 10px 0 rgba(0, 0, 0, 0.1)'
      }"
    >
      <div class="title">
        <span>知识点列表</span
        ><span class="data-tip">{{
          activeTab === 'right-rate' ? '正确率' : '掌握度'
        }}</span>
      </div>
      <el-scrollbar height="90%">
        <a-tree
          :tree-data="[knowledgeTree]"
          :fieldNames="{
            key: 'id',
            title: 'title',
            children: 'children'
          }"
          blockNode
          @expand="onExpand"
          :expandedKeys
          style="padding-right: 1vw"
        >
          <template #title="tree">
            <div class="point-title">
              <span>{{ tree.name }}</span>
              <span
                v-if="getCurRate(tree)"
                class="correct"
                :style="{ color: getColorByRate(getCurRate(tree)) }"
                >{{ (getCurRate(tree) * 100).toFixed(2) + '%' }}</span
              >
              <span v-if="!getCurRate(tree)" style="color: #ccc">--</span>
            </div>
          </template>
        </a-tree>
      </el-scrollbar>

      <div class="show-btn" @click="switchDrawer">
        知识点体系
        <img src="@/assets/images/target-boost/icon-switch.svg?url" />
      </div>
      <div class="show-list" v-if="open" @click="isShowList = true">
        <img src="@/assets/images/target-boost/enlarge.svg?url" />
      </div>
    </div>
    <div class="graph-container">
      <div class="graph" ref="chart"></div>
      <div class="show-switch" @click="onSwitchD3Graph" title="点击切换图谱">
        <span>新视图</span>
        <img src="@/assets/images/target-boost/icon-switch-graph.svg?url" />
      </div>
    </div>

    <el-scrollbar height="90vh" class="aside" v-if="isShowDetail">
      <DetailLeft
        v-if="activeTab === 'right-rate'"
        v-model:sidebarData="sidebarData"
        @close="isShowDetail = false"
        @toDetail="emit('toDetail', null, $event)"
        :changeChart
        showClose
        showDetail
        :selectTime
        :currentGradeNum
        :subjectId
        :classId
      />
      <mastery-point-detail
        v-else
        :selectTime="selectTime"
        v-model:sidebarData="sidebarData"
        :knowledgeId="knowledgeId"
        :showClose="true"
        :classId="classId"
        :currentGradeNum="currentGradeNum"
        :subjectId="subjectId"
        @close="isShowDetail = false"
        @toDetail="emit('toDetail', null, $event)"
      ></mastery-point-detail>
    </el-scrollbar>
    <template v-else>
      <Sidebar
        v-if="activeTab === 'right-rate'"
        class="aside"
        v-model:isCompare="isCompare"
        v-model:currentTabIndex="currentTabIndex"
        v-model:sidebarData="sidebarData"
        :knowledgeTree="detailData"
        :count="curCount(knowledgeTree)"
        :listWeaknesses
        :masteredKnowledgePoints
        :unmasteredKnowledgePoints
        :knowledgeId
        :strengthsAndWeaknesses
        :getAllParentNodes
        :compareLabel
        :selectTime
        :currentGradeNum
        :subjectId
        :classId
        @changeDetail="changeDetail"
        @changeGraph="changeGraph"
        @toDetail="emit('toDetail', null, $event)"
        @showDetail="isShowDetail = true"
      />
      <mastery-level-sidebar
        v-else
        class="aside"
        :selectTime="selectTime"
        v-model:sidebarData="sidebarData"
        :isShowDetail="isShowDetail"
        :knowledgeId="knowledgeId"
        :classId="classId"
        :currentGradeNum="currentGradeNum"
        :listWeaknesses="listWeaknesses"
        :masteredKnowledgePoints="masteredKnowledgePoints"
        :unmasteredKnowledgePoints="unmasteredKnowledgePoints"
        @toDetail="emit('toDetail', null, $event)"
        @showDetail="isShowDetail = true"
      />
    </template>
  </div>
</template>
<script setup>
import {
  ref,
  watch,
  onMounted,
  onUnmounted,
  nextTick,
  defineModel,
  inject
} from 'vue'

import { useRoute } from 'vue-router'

import MasteryLevelSidebar from '@/views/target-boost/target-knowledge-point/components/MasteryLevelSidebar.vue'
import MasteryPointDetail from '@/views/target-boost/target-knowledge-point/components/MasteryPointDetail.vue'
import DetailLeft from '@/views/target-boost/target-knowledge-point/components/DetailLeft.vue'
import Sidebar from '@/views/target-boost/target-knowledge-point/components/Sidebar.vue'

import { useD3Graph } from './hooks'
import { getColorByRate } from '@/views/target-boost/utils'

const route = useRoute()

const emit = defineEmits(['toDetail'])

const onSwitchD3Graph = inject('onSwitchD3Graph')
const props = defineProps({
  selectObj: Object,
  knowledgeTree: Object,
  currentGradeNum: Number,
  subjectId: Number,
  classId: String,
  selectTime: Array,
  isLoading: Boolean,
  nodeLookup: Object,
  compareLabel: String,
  activeTab: String
})

// 列表展示
const isShowList = defineModel('isShowList')

// 知识点抽屉
const expandedKeys = ref([])

const onExpand = value => {
  expandedKeys.value = value
}

const onSelect = (checkedKeys, { node }) => {
  strengthsAndWeaknesses.value.strengthList = []
  strengthsAndWeaknesses.value.weaknessList = []
  console.log(node)
  detailData.value = JSON.parse(JSON.stringify(node.dataRef))
  changeChart()
}

const knowledgeDrawer = ref(null)
const open = ref(false)
const switchDrawer = () => {
  open.value = !open.value
}
const handleClickOutside = event => {
  console.log(knowledgeDrawer.value)
  if (!knowledgeDrawer.value) {
    return
  }
  if (!knowledgeDrawer.value?.contains(event.target)) {
    open.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

const getCurRate = data => {
  if (props.activeTab === 'right-rate') {
    if (route.query.studentId) {
      return data.personal_rate
    }
    return data.class_rate
  } else {
    if (route.query.studentId) {
      return data.mastery_rate?.personal_rate
    }
    return data.mastery_rate?.class_rate
  }
}

const curCount = node => {
  return route.query.studentId ? node?.personal_count : node?.class_count
}

const chart = ref(null)
const option = {
  tooltip: e => {
    const t = e.color
    console.log(e)
    // 掌握度
    if (props.activeTab === 'mastery-level') {
      if (route.query.studentId) {
        return `<div>${
          e.name
        }</div>\n        <div style="color: ${t}">掌握度：${(
          e.mastery_rate.personal_rate * 100
        ).toFixed(2)}%</div>\n  ${
          isCompare.value
            ? `<div>对比 ${props.compareLabel}</div>\n <div >掌握度：${(
                e.mastery_rate.grade_rate * 100
              ).toFixed(2)}%</div>\n`
            : ''
        }       <div style="color: #999; font-size: 14px; margin-top: 10px;">点击“知识点”查看详情</div>\n        `
      } else {
        return `<div>${
          e.name
        }</div>\n        <div style="color: ${t}">掌握度：${(
          e.mastery_rate.class_rate * 100
        ).toFixed(2)}%</div>\n ${
          isCompare.value
            ? `<div>对比 ${props.compareLabel}</div>\n <div >掌握度：${(
                e.mastery_rate.grade_rate * 100
              ).toFixed(2)}%\n`
            : ''
        }        <div style="color: #999; font-size: 14px; margin-top: 10px;">点击“知识点”查看详情</div>\n        `
      }
    } else {
      // 正确率
      if (route.query.studentId) {
        return `<div>${
          e.name
        }</div>\n        <div style="color: ${t}">正确率：${(
          e.personal_rate * 100
        ).toFixed(2)}%  习题量：${e.personal_count}</div>\n  ${
          isCompare.value
            ? `<div>对比 ${props.compareLabel}</div>\n <div >正确率：${(
                e.grade_rate * 100
              ).toFixed(2)}%  习题量：${e.grade_count}</div>\n`
            : ''
        }       <div style="color: #999; font-size: 14px; margin-top: 10px;">点击“知识点”查看详情</div>\n        `
      }

      return `<div>${e.name}</div>\n        <div style="color: ${t}">正确率：${(
        e.class_rate * 100
      ).toFixed(2)}%  习题量：${e.class_count}</div>\n ${
        isCompare.value
          ? `<div>对比 ${props.compareLabel}</div>\n <div >正确率：${(
              e.grade_rate * 100
            ).toFixed(2)}%  习题量：${e.grade_count}</div>\n`
          : ''
      }        <div style="color: #999; font-size: 14px; margin-top: 10px;">点击“知识点”查看详情</div>\n        `
    }
  },
  tooltipsClass: 'zh_graph_tooltips',
  clickNode: d => {
    // currNode.value = d
    // selectedKeys.value = [d.data.id]
    isShowDetail.value = true
    currentNode = JSON.parse(JSON.stringify(d.data))
    console.log(d.data)

    sidebarData.value = JSON.parse(JSON.stringify(d.data))
  }
}
function getItemStyle(rate, count, node) {
  const base = {
    borderColor: '#fff',
    borderWidth: 1,
    opacity: 3
  }

  if (isCompare.value) {
    if (node.grade_rate === rate && count) {
      return {
        color: '#D46262',
        ...base
      }
    }
    if (node.grade_count > 0 && rate === 0 && count) {
      return {
        color: '#D46262',
        ...base
      }
    }
    if (node.grade_count === 0 && count) {
      return {
        color: '#D46262',
        ...base
      }
    }
    if (count === 0) {
      return {
        color: '#E0E0E0',
        ...base
      }
    }

    if (node.grade_rate > rate) {
      return {
        color: '#D46262',
        ...base
      }
    } else {
      return {
        color: '#18783B',
        ...base
      }
    }
  }
  if (rate >= 0.95) {
    return {
      color: '#19783B' || '#18783B' || '#6FA976',
      ...base
    }
  } else if (rate >= 0.85) {
    return {
      color: '#32B16C' || '#4EC680',
      ...base
    }
  } else if (rate >= 0.8) {
    return {
      color: '#B3D465' || '#71D764',
      ...base
    }
  } else if (rate >= 0.6) {
    return {
      color: '#EC6941' || '#FF6D65',
      ...base
    }
  } else if (rate > 0 || (rate === 0 && count !== 0)) {
    return {
      color: '#D92325' || '#D46262',
      ...base
    }
  } else {
    return {
      color: '#CCCCCC' || '#E0E0E0',
      ...base
    }
  }
}
function getSymbolSize(value, depth, node) {
  if (
    (isCompare.value && value === 0 && node.grade_count === 0) ||
    (!isCompare.value && value === 0)
  ) {
    return 8
  }
  // 根据层级返回不同的大小
  switch (depth) {
    case 1:
      return 25
    case 2:
      return 20
    case 3:
      return 15
    default:
      return 12
  }
}

// 薄弱知识点列表
const listWeaknesses = ref([])
// 优劣势列表
const strengthsAndWeaknesses = ref({
  strengthList: [],
  weaknessList: []
})
// 已掌握知识点列表
const masteredKnowledgePoints = ref([])
// 待掌握知识点列表
const unmasteredKnowledgePoints = ref([])
const isCompare = defineModel('isCompare')
const currentTabIndex = defineModel('currentTabIndex')
const isComputed = ref(false)

// 给知识点树添加颜色样式以及添加弱项知识点,这个函数会被执行很多次，到时候想办法优化
function applyItemStyle(data, depth = 1) {
  const processNode = (node, depth) => {
    let nodeRate, nodeCount

    if (props.activeTab === 'mastery-level') {
      if (route.query.studentId) {
        nodeRate = node.mastery_rate.personal_rate
        nodeCount = node.mastery_rate.personal_count
      } else {
        nodeRate = node.mastery_rate?.class_rate || 0
        nodeCount = node.mastery_rate?.class_count || 0
      }
    } else {
      if (route.query.studentId) {
        nodeRate = node.personal_rate
        nodeCount = node.personal_count
      } else {
        nodeRate = node.class_rate
        nodeCount = node.class_count
      }
    }

    node.symbolSize = getSymbolSize(nodeCount, depth, node)
    node.itemStyle = getItemStyle(nodeRate, nodeCount, node)

    // 如果已经计算过了就不需要再计算了
    if (!isComputed.value) {
      // 薄弱点计算
      if (nodeRate < 0.6 && nodeCount > 0) {
        listWeaknesses.value.push(node)
      }
      // 已掌握知识点
      if (nodeRate >= 0.8) {
        masteredKnowledgePoints.value.push(node)
      }
      // 待掌握知识点
      if (nodeRate >= 0.6 && nodeRate < 0.8) {
        unmasteredKnowledgePoints.value.push(node)
      }
      // 优劣势计算
      const compareRate = nodeRate - node.grade_rate
      node.compare_rate = compareRate
      if (compareRate > 0 && node.class_count && node.grade_count) {
        strengthsAndWeaknesses.value.strengthList.push(node)
      } else if (nodeRate !== 0 && compareRate > 0 && nodeCount) {
        strengthsAndWeaknesses.value.strengthList.push(node)
      } else if (nodeRate === 0 && compareRate === 0 && nodeCount) {
        strengthsAndWeaknesses.value.weaknessList.push(node)
      } else if (compareRate < 0) {
        strengthsAndWeaknesses.value.weaknessList.push(node)
      }
    }

    if (node.children) {
      applyItemStyle(node.children, depth + 1)
    }
  }

  if (Array.isArray(data)) {
    data.forEach(node => processNode(node, depth))
  } else {
    processNode(data, depth)
  }
}

const isShowDetail = ref(false)
// 这个文件中使用了JSON去深拷贝是为了解除响应式，修改这个响应式的数据会导致性能卡顿
const detailData = ref(JSON.parse(JSON.stringify(props.knowledgeTree)))
const sidebarData = ref(null)
const changeDetail = detail => {
  sidebarData.value = JSON.parse(JSON.stringify(detail))
  isShowDetail.value = true
}

// 根据isClassRate是使用的参数来决定是使用class_rate还是grade_rate
const changeGraph = async iscompare => {
  if (iscompare === isCompare.value) {
    return
  }
  isCompare.value = iscompare
  await nextTick()
  const newData = JSON.parse(JSON.stringify(detailData.value))

  console.log(iscompare)

  applyItemStyle(newData)
  detailData.value = newData
  createChart()
}

// const { addEvent, showLoading, hideLoading } = useEcharts(chart, option)
console.log(chart.value)

const { createChart } = useD3Graph(detailData, chart, option)

const changeChart = async () => {
  // 重置薄弱点
  listWeaknesses.value = []

  isComputed.value = false

  // 给知识点树添加颜色样式以及添加弱项知识点
  applyItemStyle(detailData.value)
  console.log(strengthsAndWeaknesses.value.weaknessList)
  isComputed.value = true
  // 这个listWeaknesses在applyItemStyle改变了数据，所以需要重新排序
  console.log(listWeaknesses.value)
  if (route.query.studentId) {
    listWeaknesses.value = listWeaknesses.value.sort(
      (a, b) => a.personal_rate - b.personal_rate
    )
  } else {
    listWeaknesses.value = listWeaknesses.value.sort(
      (a, b) => a.class_rate - b.class_rate
    )
  }

  // 优劣势计算, 并截取前15个
  strengthsAndWeaknesses.value.strengthList =
    strengthsAndWeaknesses.value.strengthList
      .sort((a, b) => a.compare_rate - b.compare_rate)
      .slice(0, 15)
  strengthsAndWeaknesses.value.weaknessList =
    strengthsAndWeaknesses.value.weaknessList
      .sort((a, b) => a.compare_rate - b.compare_rate)
      .slice(0, 15)
  await nextTick()
  console.log(chart.value)
  createChart()
}
const rootId = ref(-1)
// 监听选择改变
watch(
  () => [props.knowledgeTree, props.isLoading, props.activeTab],
  () => {
    if (props.knowledgeTree === null) {
      return
    }
    rootId.value = props.knowledgeTree.id
    expandedKeys.value = [rootId.value]
    if (props.isLoading) {
      // showLoading()
    } else {
      if (props.knowledgeTree?.id === rootId.value) {
        if (detailData.value) {
          detailData.value = JSON.parse(
            JSON.stringify(props.nodeLookup[detailData.value.id])
          )
        } else {
          detailData.value = JSON.parse(JSON.stringify(props.knowledgeTree))
        }
      } else {
        console.log(props.knowledgeTree)
        return
      }
      changeChart()
    }
  },
  {
    immediate: true
  }
)

// 获取所有父节点
const getAllParentNodes = nodeId => {
  const parents = []
  let currentNode = props.nodeLookup[nodeId]
  while (currentNode && currentNode.parentId !== null) {
    currentNode = props.nodeLookup[currentNode.parentId]
    if (currentNode) {
      parents.push(currentNode)
    }
  }

  return parents.reverse()
}

let currentNode = JSON.parse(JSON.stringify(props.knowledgeTree))
console.log(currentNode)
</script>
<!-- eslint-disable -->
<style lang="less">
.zh_graph_tooltips {
  z-index: 20;
  border-radius: 8px;
  padding: 0.5vw 0.8vw;
  width: 20vw;
  background: #fff;
  border: 0.1vw solid #ccc;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  opacity: 0;
}
</style>

<style lang="less" scoped>
.graph-analyze {
  position: relative;
  display: flex;
  height: 100%;
  overflow: hidden;

  .knowledge-drawer {
    position: absolute;
    top: calc(50% + 30px);
    height: 85%;
    width: 18vw;
    padding: 0 0 20px 20px;
    background-color: #fff;
    box-shadow: 3px 0 10px #ccc;
    z-index: 1;

    :deep(.ant-tree-treenode) {
      width: 100%;
      .ant-tree-node-content-wrapper {
        display: inline-block;
        width: 100%;
      }
      .ant-tree-node-selected {
        background-color: #367cff69;
      }
    }

    .title {
      font-size: 18px;
      font-weight: 500;
      margin-top: 30px;
      margin-bottom: 25px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-right: 1vw;

      .data-tip {
        font-size: 16px;
      }
    }

    .point-title {
      width: 100%;
      display: flex;
      justify-content: space-between;
      .correct {
        margin-left: px;
      }
    }

    .show-btn {
      position: absolute;
      top: 20%;
      transform: translateY(-50%);
      right: -61px;
      width: 61px;
      padding: 23px;
      text-align: center;
      background-color: #e5f5ff;
      color: #040b1ad9;
      cursor: pointer;
      border-radius: 0 10px 10px 0;

      img {
        width: 15px;
      }
    }

    .show-list {
      position: absolute;
      top: 40%;
      transform: translateY(-50%);
      right: -61px;
      width: 61px;
      padding: 20.5px;
      text-align: center;
      background-color: #e5f5ff;
      color: #040b1ad9;
      cursor: pointer;
      border-radius: 0 10px 10px 0;
    }
  }
  .graph-container {
    position: relative;
    flex: 1;
    box-sizing: border-box;
    height: 90vh;
    background-color: #fff;
    border-radius: 10px;

    .graph {
      position: relative;
      flex: 1;
      box-sizing: border-box;
      height: 100%;
      background-color: #fff;
    }

    .show-switch {
      position: absolute;
      left: 43px;
      bottom: 20px;
      padding: 20.5px;
      text-align: center;
      color: #040b1ad9;
      cursor: pointer;
      font-size: 20px;
      img {
        width: 25px;
        margin-left: 10px;
      }
    }
  }

  .aside {
    margin-left: 20px;
    width: 388px;
    height: 90vh;
    border-radius: 10px;
    overflow-y: auto;
  }

  :deep(.left-container) {
    padding-top: 0;
  }
}
</style>
